package com.candy.control;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@CrossOrigin
public class FileUploadController {
        @Value("${file.uploadFolder}")
        String  dir;

        @RequestMapping("/upload")
        public String upload(@RequestParam("image") MultipartFile file) throws IOException {

            SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
            //准备文件夹
            String format = sdf.format(new Date());
//        String  dir="E:\\CodeSpace\\img";
//        根据指定路径创建文件所放置的文件夹
            File folder = new File(dir,format);
//        如果该文件夹不存在，则在本地创建一个文件夹
            if(!folder.exists()){
                folder.mkdirs();//
            }
            //准备文件

            String oldName = file.getOriginalFilename();//获取后缀
            String fileName= UUID.randomUUID().toString() +oldName.substring(oldName.lastIndexOf("."));
            File file1 = new File(folder, fileName);
            //上传
            file.transferTo(file1);
            String imgUrl="http://localhost:8086"+format+fileName;
//        model.addAttribute("imgSrc",imgUrl);
            //组装url
            return imgUrl;
        }
    }


